package com.hag.equipment_server.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

public class MessageDecoder extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        short SOF = in.readUnsignedByte();
        if(SOF != 0xaa){
            return;
        }
        long LEN = in.readUnsignedIntLE();
        short ACK_VER = in.readUnsignedByte();
        short COMMAND_ID = in.readUnsignedByte();
        int CRC16 = in.readUnsignedShort();
        Header header = new Header(SOF,LEN,ACK_VER,COMMAND_ID,CRC16);

        ByteBuf body = in.readBytes((int)LEN - 9 - 4);

        ByteBuf tail = in.readBytes(4);

        Message message = new Message();
        message.setHeader(header);
        message.setBody(body);
        message.setTail(tail);

        out.add(message);
    }
}

